package com.software.levelupserver.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.software.levelupserver.entity.User;
import com.software.levelupserver.exception.BizException;
import com.software.levelupserver.utils.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtCheckFilter extends OncePerRequestFilter {
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private HandlerExceptionResolver handlerExceptionResolver;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(httpServletRequest.getRequestURI().equals("/levelup/login")
                || httpServletRequest.getRequestURI().equals("/levelup/user/register")
                || httpServletRequest.getRequestURI().equals("/levelup/user/getCodeForRegister")
                || httpServletRequest.getRequestURI().equals("/levelup/user/getCodeForUpdatePassword")
                || httpServletRequest.getRequestURI().equals("/levelup/user/findAllUsers")
//                || httpServletRequest.getRequestURI().startsWith("/levelup/user/")
                || httpServletRequest.getRequestURI().equals("/levelup/task/countAllTask")
				|| httpServletRequest.getRequestURI().equals("/levelup/systemTask/addSystemTask")
//                || httpServletRequest.getRequestURI().equals("/levelup/user/updateLoginTime")
//                || httpServletRequest.getRequestURI().startsWith("/levelup/task/")
//                || httpServletRequest.getRequestURI().startsWith("/levelup/label/")
                || httpServletRequest.getRequestURI().equals("/levelup/user/updatePassword")){
            doFilter(httpServletRequest,httpServletResponse,filterChain);
            return;
        }
        String authorization = httpServletRequest.getHeader("Authorization");
        if(StringUtils.isEmpty(authorization)){
            handlerExceptionResolver.resolveException(httpServletRequest,httpServletResponse,null,new BizException("请重新登录"));
        }
        String jwt = authorization.replace("level-up ", "");
        if(StringUtils.containsWhitespace(jwt)){
            handlerExceptionResolver.resolveException(httpServletRequest,httpServletResponse,null,new BizException("请重新登录"));
        }

        try {
            jwtUtil.verifyJwt(jwt);
        }catch (Exception e){
            handlerExceptionResolver.resolveException(httpServletRequest,httpServletResponse,null,new BizException(e.getMessage()));
            return;
        }
        String user = jwtUtil.getUserFromJwt(jwt);
        List<String> authList = jwtUtil.getUserAuthFromJwt(jwt);
        User user1 = objectMapper.readValue(user, User.class);
        //List<SimpleGrantedAuthority> authorityList = authList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user1,null,authorityList);
        SecurityContextHolder.getContext().setAuthentication(token);
        doFilter(httpServletRequest,httpServletResponse,filterChain);
    }
}
